<template>
	<view class="layout">
				<wd-navbar title="色层涂布" left-text="返回" @click-left="uni.navigateBack" left-arrow right-text="保存"  @click-right="onSubmit"/>
		<wd-toast />
		
		<!-- 工序记录状态显示 -->
		<wd-cell-group title="工序记录状态">
			<wd-cell v-if="hasExistingRecord" title="完成时间" :value="processRecord?.productionTime ? dayjs(processRecord.productionTime).format('YYYY-MM-DD HH:mm:ss') : ''" />
		</wd-cell-group>
		
		<wd-form ref="form" class="form" :model="formState">
			<wd-cell-group border>
				<wd-input label="米数" prop="name" type="number" clearable v-model="formState.length"
					placeholder="请输入生产米数" :rules="[{ required: true, message: '请填生产米数' }]" />
				<wd-input label="接头数" prop="password" clearable v-model="formState.linkCount" type="number"
					placeholder="请输入接头数" :rules="[{ required: true, message: '请填写接头数' }]" />
				<wd-textarea v-model="formState.note" prop="note" placeholder="请填写说明" />
			</wd-cell-group>
		</wd-form>
		<wd-cell-group title="事件登记">
			<template #value>
				<wd-button size="small" type="icon" icon="add" @click="record.open = true" />
				<wd-action-sheet v-model="record.open" :actions="record.actions" @select="onSelect" />
			</template>
			<wd-cell v-for="(item,index) in events" :title="item.name"
				:value="dayjs(item.eventTime).format('YYYY-MM-DD HH:mm:ss')" @click="events.splice(index, 1)" is-link />
			<!-- 显示已存在的工序异常记录 -->
			<wd-cell 
				v-for="(exception, index) in processExceptions" 
				:key="`exception-${index}`"
				:title="`异常: ${exception.exceptionName}`"
				:value="exception.createTime ? dayjs(exception.createTime).format('YYYY-MM-DD HH:mm:ss') : ''"
			/>
		</wd-cell-group>
	</view>
</template>

<script setup lang="ts">
	import { reactive, ref, onMounted } from 'vue';
	import dayjs from 'dayjs';
	import { useToast } from '@/uni_modules/wot-design-uni'
	import { C91330326Ma287Bmm6JService, ExceptionService, ProcessService, type AddProcessStepRequest, type EditProcessStepRequest } from '@/services';
	import useApp from '@/stores/app';
	const app = useApp();
	const toast = useToast()
	const STEP = 2;
	
	onMounted(async () => {
		await loadProcessStepRecord();
		await loadExceptionEvents();
	});
	const step = app.work?.step_2 ?? {
		workId: app.code,
		length: 0,
		linkCount: 0,
		note: ''
	};
	const formState = reactive(step);
	const app_events = app.getEvents(STEP);
	// 初始化为空的事件列表，不包含已有异常记录
	const events = ref([]);
	const record = reactive({
		open: false,
		actions: []
	});
	const onSelect = ({ item, index }) => {
		events.value.push({
			name: item.name,
			eventTime: dayjs(),
			exceptionId: item.exceptionId // 保存异常ID
		});
	}
	// 工序记录状态
	const processRecord = ref<any>(null);
	const hasExistingRecord = ref(false);
	const processExceptions = ref([]);

	// 获取色层涂布工序的processId
	const getProcessId = async () => {
		try {
			const result = await ProcessService.getProcessList(1, 10);
			if (result.code === 200) {
				const process = result.rows.find(p => p.processName === '色层涂布');
				return process?.processId;
			}
		} catch (error) {
			console.error('获取工序列表失败:', error);
		}
		return null;
	};

	// 加载工序记录
	const loadProcessStepRecord = async () => {
		try {
			if (!app.code) {
				console.error('流程卡号不存在');
				return;
			}
			
			const processId = await getProcessId();
			if (!processId) {
				console.error('未找到色层涂布工序');
				return;
			}
			
			// 调用新的API获取工序记录
			const stepResult = await ProcessService.getProcessStepByIds(app.code, processId);
			
			if (stepResult.code === 200 && stepResult.data && stepResult.data.length > 0) {
				console.log('已存在工序记录:', stepResult.data);
				// API返回数组，取第一个记录
				const record = stepResult.data[0];
				processRecord.value = record;
				hasExistingRecord.value = true;
				
				// 如果有记录，可以预填充生产长度
				if (record.productionLength) {
					formState.length = record.productionLength;
				}
				
				// 如果有接头数，预填充接头数
				if (record.jointsCount !== undefined && record.jointsCount !== null) {
					formState.linkCount = record.jointsCount;
				}
				
				// 如果有说明，预填充说明
				if (record.description) {
					formState.note = record.description;
				}
				
				// 加载工序异常记录
				await loadProcessExceptions(record.id);
			} else {
				console.log('暂无工序记录');
				hasExistingRecord.value = false;
			}
		} catch (error) {
			console.error('加载工序记录失败:', error);
		}
	};
	
	// 加载工序异常记录（仅在工序记录状态区域显示）
	const loadProcessExceptions = async (processStepId) => {
		try {
			console.log('loadProcessExceptions 调用参数:', { processCardId: app.code, processStepId });
			if (!app.code || !processStepId) {
				console.log('参数缺失，跳过异常加载', { processCardId: app.code, processStepId });
				return;
			}
			
			// 使用工序记录返回的id作为processStepId
			const exceptionResult = await ProcessService.getProcessStepExceptions(app.code, processStepId);
			console.log('异常接口响应:', exceptionResult);
			
			if (exceptionResult.code === 200 && exceptionResult.data) {
				// 在工序记录状态区域显示异常信息
				processExceptions.value = exceptionResult.data.map(exception => ({
					exceptionName: exception.exceptionName,
					createTime: exception.createTime
				}));
				console.log('处理后的工序异常记录:', processExceptions.value);
				console.log('processExceptions.value.length:', processExceptions.value.length);
			} else {
				console.log('异常接口返回异常:', exceptionResult);
			}
		} catch (error) {
			console.error('加载工序异常失败:', error);
		}
	};

	// 加载异常事件数据
	const loadExceptionEvents = async () => {
		try {
			const response = await ExceptionService.getExceptionList(1, 10);
			if (response && response.rows && Array.isArray(response.rows)) {
				// 将异常事件数据转换为actions格式，保存异常ID和名称
				record.actions = response.rows
					.filter(item => item.exceptionName) // 过滤掉没有名称的项
					.map(item => ({
						name: item.exceptionName,
						exceptionId: item.id || item.exceptionId // 保存异常ID
					}));
			} else {
				record.actions = [];
			}
		} catch (error) {
			console.error('加载异常事件失败:', error);
			record.actions = [];
		}
	};

	const onSubmit = async () => {
		// 如果已存在记录，询问用户是否要更新
		if (hasExistingRecord.value) {
			uni.showModal({
				title: '提示',
				content: '该工序已有记录，是否要更新？',
				success: async (res) => {
					if (res.confirm) {
						await submitProcessStep();
					}
				}
			});
		} else {
			await submitProcessStep();
		}
	};

	const submitProcessStep = async () => {
		toast.loading('保存中...')
		try {
			if (!app.code) {
				toast.error("流程卡号不存在");
				return;
			}
			
			const processId = await getProcessId();
			if (!processId) {
				toast.error("未找到色层涂布工序");
				return;
			}
			
			// 准备事件异常数据
			const processStepException = events.value.map(event => ({
				processCardId: app.code,
				exceptionId: event.exceptionId // 使用正确的异常ID
			})).filter(item => item.exceptionId); // 过滤掉没有异常ID的项
			
			const currentTime = new Date().toISOString();
			
			let response;
			if (hasExistingRecord.value && processRecord.value?.id) {
				// 修改工序记录
				const editRequest: EditProcessStepRequest = {
					id: processRecord.value.id,
					processCardId: app.code,
					processId: processId,
					// productionType 不传，让后端自行处理
					productionLength: String(formState.length || 0),
					productionTime: currentTime,
					jointsCount: formState.linkCount || 0, // 接头数
					description: formState.note || '', // 说明
					processStepException: processStepException
				};
				response = await ProcessService.editProcessStep(editRequest);
			} else {
				// 新增工序记录
				const addRequest: AddProcessStepRequest = {
					processCardId: app.code,
					processId: processId,
					// productionType 不传，让后端自行处理
					productionLength: String(formState.length || 0),
					productionTime: currentTime,
					jointsCount: formState.linkCount || 0, // 接头数
					description: formState.note || '', // 说明
					processStepException: processStepException
				};
				response = await ProcessService.addProcessStep(addRequest);
			}
			
			if (response.code === 200) {
				toast.success('保存成功');
				// 更新状态
				hasExistingRecord.value = true;
				await loadProcessStepRecord(); // 重新加载记录
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} else {
				toast.error(response.msg || "保存失败，请重试!");
			}
		} catch (error) {
			console.error('保存失败:', error);
			toast.error("保存失败，请重试!")
		} finally {
			toast.close();
		}
	}
</script>

<style scoped>
	.layout {
		padding: 16rpx;
	}

	:deep(.wd-cell__left) {
		width: 120px !important;
		flex: none;
	}
</style>
<style>

</style>